// For help, see https://github.com/koajs/router
const fs = require('fs');
const path = require('path');
const cosService = require('../cosService');

module.exports = (router) => {
  // 数据文件路径
  const dataFilePath = path.join(__dirname, '../../public/project.json');

  // 读取数据文件（同步，仅从本地读取）
  function readDataFile() {
    try {
      if (fs.existsSync(dataFilePath)) {
        const data = fs.readFileSync(dataFilePath, 'utf8');
        const localData = JSON.parse(data);
        return localData;
      }
    } catch (error) {
      console.error('读取本地数据文件失败:', error);
    }
    
    // 返回默认数据结构，包含默认分组：产品组和前端组
    return { 
      projectGroups: [
        {
          id: 'group-product',
          name: '产品组',
          createdAt: new Date(),
          updatedAt: new Date()
        },
        {
          id: 'group-frontend',
          name: '前端组',
          createdAt: new Date(),
          updatedAt: new Date()
        }
      ], 
      projects: [] 
    };
  }

  // 写入数据文件（本地+云端同步）
  function writeDataFile(data) {
    try {
      // 先写入本地文件
      fs.writeFileSync(dataFilePath, JSON.stringify(data, null, 2), 'utf8');
      console.log('数据写入本地文件成功');
      
      // 异步同步到云端（不阻塞主流程）
      cosService.syncToCloud(data);
      
      return true;
    } catch (error) {
      console.error('写入数据文件失败:', error);
      return false;
    }
  }

  // CORS中间件
  router.use(async (ctx, next) => {
    // 设置CORS头部
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
    
    // 处理预检请求
    if (ctx.method === 'OPTIONS') {
      ctx.status = 200;
      return;
    }
    
    await next();
  });

  router.get('/cgi-bin/init', (ctx) => {
    ctx.body = 'Hello whistle111.';
  });

  // 获取所有项目
  router.get('/cgi-bin/api/project', async (ctx) => {
    // const cloudData = await cosService.downloadData();
    // ctx.body = {
    //   success: true,
    //   data: cloudData
    // };
    try {
      // 优先尝试从云端获取数据
      let data = await cosService.downloadData();
      
      // 如果云端没有数据，则读取本地文件
      if (!data) {
        data = readDataFile();
        console.log('从本地文件读取数据:', data);
      }
      
      ctx.body = {
        success: true,
        data: data
      };
    } catch (error) {
      console.error('获取项目数据失败:', error);
      // 如果出错，返回本地数据作为兜底
      const localData = readDataFile();
      ctx.body = {
        success: true,
        data: localData
      };
    }
  });

  // 创建项目
  router.post('/cgi-bin/api/project', async (ctx) => {
    try {
      // 优先尝试从云端获取数据，如果失败则读取本地文件
      let data = await cosService.downloadData();
      if (!data) {
        data = readDataFile();
        console.log('创建项目时从本地文件读取数据:', data);
      }
      
      const { name, description, groupId, environments } = ctx.request.body;
      if (!name) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '项目名称不能为空'
        };
        return;
      }
      
      // 验证分组是否存在
      if (groupId && !data.projectGroups.find(g => g.id === groupId)) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '指定的项目分组不存在'
        };
        return;
      }

      const newProject = {
        id: generateUUID(),
        name,
        description: description || '',
        groupId: groupId || data.projectGroups[0]?.id || '',
        environments: (environments || []).map(env => ({
          id: generateUUID(),
          name: env.name,
          type: env.type,
          hosts: env.hosts || [],
        })),
        createdAt: new Date(),
        updatedAt: new Date()
      };
      data.projects.push(newProject);
      
      // 保存到本地文件
      writeDataFile(data);
      
      // 尝试同步到云端
      try {
        await cosService.uploadData(data);
      } catch (uploadError) {
        console.warn('云端同步失败，但不影响本地操作:', uploadError.message);
      }
      
      ctx.body = {
        success: true,
        data: newProject
      };
    } catch (error) {
      console.error('创建项目失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '项目创建失败: ' + error.message
      };
    }
  });

  // 更新项目
  router.put('/cgi-bin/api/project/:id', async (ctx) => {
    try {
      const data = await cosService.downloadData();
      const projectIndex = data.projects.findIndex(p => p.id === ctx.params.id);
      if (projectIndex === -1) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '项目不存在'
        };
        return;
      }
  
      const { name, description, groupId, environments } = ctx.request.body;
      
      // 验证分组是否存在
      if (groupId && !data.projectGroups.find(g => g.id === groupId)) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '指定的项目分组不存在'
        };
        return;
      }
  
      const updatedProject = {
        ...data.projects[projectIndex],
        name: name || data.projects[projectIndex].name,
        description: description !== undefined ? description : data.projects[projectIndex].description,
        groupId: groupId || data.projects[projectIndex].groupId,
        updatedAt: new Date()
      };
  
      if (environments) {
        updatedProject.environments = environments.map(env => ({
          id: env.id || generateUUID(),
          name: env.name,
          type: env.type,
          hosts: env.hosts || [],
          isActive: env.isActive || false
        }));
      }
  
      data.projects[projectIndex] = updatedProject;
      
      await cosService.uploadData(data);
      
      ctx.body = {
        success: true,
        data: updatedProject
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '项目更新失败'
      };
    }
  });

  // 删除项目
  router.delete('/cgi-bin/api/project/:id', async (ctx) => {
    try {
      const cloudData = await cosService.downloadData();
      const projectIndex = cloudData.projects.findIndex(p => p.id === ctx.params.id);
      if (projectIndex === -1) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '项目不存在'
        };
        return;
      }

      cloudData.projects.splice(projectIndex, 1);
      await cosService.uploadData(cloudData);
      ctx.body = {
        success: true,
        message: '项目删除成功'
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '项目删除失败'
      };
    }
  });

  // ==================== 项目分组管理接口 ====================
  
  // 创建分组
  router.post('/cgi-bin/api/group', async (ctx) => {
    const { name } = ctx.request.body;
    
    if (!name) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '分组名称不能为空'
      };
      return;
    }
    try {
      const data = await cosService.downloadData();
      const group = data.projectGroups.find(g => g.name === name);
      if (group) {
        ctx.status = 401;
        ctx.body = {
          success: false,
          message: '分组已存在'
        };
        return;
      }
      const newGroup = {
        id: generateUUID(),
        name,
        createdAt: new Date(),
        updatedAt: new Date()
      };

      data.projectGroups.push(newGroup);

      await cosService.uploadData(data);

      ctx.body = {
        success: true,
        data: newGroup
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '分组创建失败'
      };
    }

  });

  // 更新分组
  router.put('/cgi-bin/api/group/:id', async (ctx) => {
    try {
      const data = await cosService.downloadData();
      const groupIndex = data.projectGroups.findIndex(g => g.id === ctx.params.id);
      if (groupIndex === -1) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '分组不存在'
        };
        return;
      }
      const { name } = ctx.request.body;
      const updatedGroup = {
        ...data.projectGroups[groupIndex],
        name: name || data.projectGroups[groupIndex].name,
        updatedAt: new Date()
      };
      data.projectGroups[groupIndex] = updatedGroup;
      await cosService.uploadData(data);
      ctx.body = {
        success: true,
        data: data.projectGroups
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '分组更新失败'
      };
    }
  });

  // 删除分组
  router.delete('/cgi-bin/api/group/:id', async(ctx) => {
    try {
      const data = await cosService.downloadData();
      const groupIndex = data.projectGroups.findIndex(g => g.id === ctx.params.id);
      if (groupIndex === -1) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '分组不存在'
        };
        return;
      }
      
      // 检查是否有项目使用该分组
      const projectsInGroup = data.projects.filter(p => p.groupId === ctx.params.id);
      if (projectsInGroup.length > 0) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: `该分组下还有 ${projectsInGroup.length} 个项目，无法删除`
        };
        return;
      }

      data.projectGroups.splice(groupIndex, 1);
      await cosService.uploadData(data);
      ctx.body = {
        success: true,
        message: '分组删除成功'
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '分组删除失败'
      };
    }
  });

  // ==================== Whistle规则管理接口 ====================
  
  // 获取当前生成的whistle规则
  router.get('/cgi-bin/api/whistle/rules', (ctx) => {
    try {
      // 直接读取 rules.txt 文件内容
      const rulesFilePath = path.join(__dirname, '../../rules.txt');
      let rulesContent = '';
      
      if (fs.existsSync(rulesFilePath)) {
        rulesContent = fs.readFileSync(rulesFilePath, 'utf8');
      }
      
      // 从数据管理器获取环境信息
      const data = readDataFile();
      const activeEnvs = [];
      data.projects.forEach(project => {
        project.environments.forEach(env => {
          if (env.isActive) {
            activeEnvs.push({
              projectId: project.id,
              projectName: project.name,
              envId: env.id,
              envName: env.name,
              envType: env.type,
              hosts: env.hosts
            });
          }
        });
      });
      
      ctx.body = {
        success: true,
        data: {
          rulesContent: rulesContent,
          activeEnvironments: activeEnvs,
          rulesFilePath: rulesFilePath,
          rulesUpdated: true
        }
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取whistle规则失败',
        error: error.message
      };
    }
  });

  // 更新 rules.txt 文件的函数
  async function updateRulesFile(rulesContent) {
    try {
      const rulesFilePath = path.join(__dirname, '../../rules.txt');
      fs.writeFileSync(rulesFilePath, rulesContent.join('\n'), 'utf8');

      return true;
    } catch (error) {
      console.error('[NoHost] 更新 rules.txt 文件失败:', error);
      throw error;
    }
  }

  // ==================== 环境激活接口 ====================
  
  // 激活环境 (实时同步优化版)
  router.post('/cgi-bin/api/activate/rules', async (ctx) => {
    const { rules } = ctx.request.body;
    updateRulesFile(rules);
    ctx.body = {
      success: true,
      message: '规则更新成功'
    };
  });

  // 取消激活环境 (实时同步优化版)
  router.post('/cgi-bin/api/project/:id/environment/:envId/deactivate', async (ctx) => {
    const startTime = Date.now();
    const data = readDataFile();
    const project = data.projects.find(p => p.id === ctx.params.id);
    
    if (!project) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '项目不存在'
      };
      return;
    }

    const environment = project.environments.find(env => env.id === ctx.params.envId);
    if (!environment) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '环境不存在'
      };
      return;
    }

    // 取消激活环境
    environment.isActive = false;

    if (writeDataFile(data)) {
      try {
        // 同时更新 rules.txt 文件 (备用)
        await updateRulesFile();
        
        // 强制刷新 Whistle 规则，确保立即生效
        await forceWhistleReload();
        
        const responseTime = Date.now() - startTime;
        
        // 设置无缓存响应头，确保前端获取最新数据
        ctx.set('Cache-Control', 'no-cache, no-store, must-revalidate');
        ctx.set('Pragma', 'no-cache');
        ctx.set('Expires', '0');
        
        ctx.body = {
          success: true,
          message: '环境取消激活成功，规则已实时更新',
          data: {
            environment: environment,
            rulesUpdated: true,
            timestamp: new Date().toISOString(),
            responseTime: responseTime,
            deactivatedHosts: environment.hosts,
            // 为前端提供强制刷新的标识
            forceRefresh: true
          }
        };
        
        // 输出日志用于调试
        console.log(`[NoHost] 环境取消激活成功 (${responseTime}ms): ${project.name} - ${environment.name}`);
        console.log(`[NoHost] 取消激活的Host规则:`, environment.hosts);
        
      } catch (ruleError) {
        console.error(`[NoHost] 更新规则文件失败:`, ruleError);
        ctx.body = {
          success: true,
          message: '环境取消激活成功，但备用规则文件更新失败',
          data: {
            environment: environment,
            error: ruleError.message,
            timestamp: new Date().toISOString()
          }
        };
      }
    } else {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '环境取消激活失败'
      };
    }
  });

  // UUID生成函数
  function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      const r = Math.random() * 16 | 0;
      const v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

};
